from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, status, BackgroundTasks
import threading
import logging
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.api.deps import get_current_user
from app.models.user import User
from app.schemas.file import FileResponse
import os
import shutil
from datetime import datetime
import uuid
from text_split import TextSplit  # 添加导入
import asyncio
from concurrent.futures import ThreadPoolExecutor
import queue

router = APIRouter()

# 配置文件上传目录
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'data')
if not os.path.exists(DATA_DIR):
    os.makedirs(DATA_DIR)

# 添加日志配置
logging.basicConfig(
    filename='file_processing.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 创建线程池和任务队列
executor = ThreadPoolExecutor(max_workers=3)  # 限制最大线程数
task_queue = queue.Queue()
processing_files = set()

def run_text_split(file_path: str):
    try:
        if file_path in processing_files:
            logging.warning(f"文件已在处理中: {file_path}")
            return
            
        processing_files.add(file_path)
        text_split = TextSplit()
        asyncio.run(text_split.start(file_path))
        logging.info(f"文件处理完成: {file_path}")
    except Exception as e:
        logging.error(f"文件处理失败: {file_path}, 错误: {str(e)}")
    finally:
        processing_files.remove(file_path)

@router.post("/upload", response_model=FileResponse)
async def upload_file(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    description: str = None,
):
    try:
        # 保存原始文件名
        file_path = os.path.join(DATA_DIR, file.filename)
        
        # 保存文件
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # 获取文件信息
        file_size = os.path.getsize(file_path)
        
        # 创建文件记录
        file_record = {
            "id": file.filename,
            "filename": file.filename,
            "file_path": file_path,
            "file_size": file_size,
            "upload_time": datetime.now(),
            "uploader_id": current_user.id,
            "description": description
        }

        # 添加异步处理任务
        async def process_file():
            text_split = TextSplit()
            await text_split.start(file_path)

        background_tasks.add_task(process_file)
        
        # 在新线程中处理文件
        thread = threading.Thread(
            target=run_text_split,
            args=(file_path,),
            daemon=True
        )
        thread.start()
        
        # 使用线程池提交任务
        future = executor.submit(run_text_split, file_path)
        
        return FileResponse(**file_record)
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件上传失败: {str(e)}"
        )

@router.get("/files", response_model=List[FileResponse])
def get_files(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        files = []
        for filename in os.listdir(DATA_DIR):
            file_path = os.path.join(DATA_DIR, filename)
            if os.path.isfile(file_path):
                files.append({
                    "id": filename,
                    "filename": filename,
                    "file_path": file_path,
                    "file_size": os.path.getsize(file_path),
                    "upload_time": datetime.fromtimestamp(os.path.getctime(file_path)),
                    "uploader_id": current_user.id,
                    "description": None
                })
        return files
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取文件列表失败: {str(e)}"
        )

@router.delete("/files/{file_id}")
def delete_file(
    file_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        file_path = os.path.join(DATA_DIR, file_id)
        if os.path.exists(file_path):
            os.remove(file_path)
            return {"message": "文件删除成功"}
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="文件不存在"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除文件失败: {str(e)}"
        )